import requests
import datetime
import time
import json
import re
import ssl
import sys
import schedule
import datetime


today = datetime.date.today()
user_day = today + datetime.timedelta(days = 1)
user_day = str(user_day)

def job():
    print('22:00开始执行')
    library()
    print('----------------')

class library():
    def __init__(self):

            user_name = "19858119179"
            user_passwd = "dmz123"
            user_room_id = ["981","981","981","981"]
            user_seat_id =[ "035","035","035","035"]
            user_startTime = ["12%3A00","12%3A30","13%3A00","13%3A30"]
            user_endTime = ["12%3A30","13%3A00","13%3A30","14%3A00"]
            user_id = "130855384"

            self.user_id = user_id
            self.user_name = user_name
            self.passwd = user_passwd
            self.room_id = user_room_id
            self.seat_id = user_seat_id
            self.startTime = user_startTime
            self.endTime = user_endTime
            self.day = user_day
            self.headers = {
                "Connection":"close",
                "User-Agent":"Dalvik/2.1.0 (Linux; U; Android 5.1.1; SM-N960F Build/JLS36C) com.chaoxing.mobile/ChaoXingStudy_3_4.3.6_android_phone_496_27 (@Kalimdor)_f491dc234e3f40608b6f380fa80b79ec"
            }

            self.session = requests.session()  # 建立一个Session
            self.session.keep_alive = False
            self.run()#开始运行
            self.session.close()


    def run(self):

         #登陆APP
        #res =  self.loginAPP(self.user_name,self.passwd)
        #if(res == False):
        #    return
        
         #获取用户uid
        #uid = self.getUserId()
        #return False
        #if(uid == False):
        #    return

       # 登陆进图书馆
        #if self.timer == 0:
        res = self.loginLibrary(self.user_id)
        if(res == False):
            return
        #开始预约图书馆
        res_1 = False
        # while res_1 == False:
        while True:
            for i in range(len(self.endTime)):
                res_1 = self.startBook(self.room_id[i],self.startTime[i],self.endTime[i],self.seat_id[i],self.day)
                # time.sleep(1)
                if (res_1 == False):
                    print("\n预约错误")
                    print("开始时间：", self.startTime[i])
                    print("结束时间：", self.endTime[i])
                    print("\n")
                else:
                    print("\n*********预约成功！*********")
                    print("您的预约信息如下:")
                    print("名字: ", self.user_name)
                    print("日期：", self.day)
                    print("房间：", self.room_id[i])
                    print("座位号：", self.seat_id[i])
                    print("开始时间：", self.startTime[i])
                    print("结束时间：", self.endTime[i])
                    print("\n")

        # print("\n*********预约成功！*********")
        # print("您的预约信息如下:")
        # print("名字: ", self.user_name)
        # print("日期：", self.day)
        # print("房间：", self.room_id)
        # print("座位号：", self.seat_id)
        # print("开始时间：", self.startTime)
        # print("结束时间：", self.endTime)



    #登陆APP
    def loginAPP(self,user_name,passwd):
        """
        :param user_name: 账号
        :param passwd: 密码
        :return: True or False
        """
        print("正在登陆APP,账号："+user_name+"，密码："+passwd)
        url = "https://passport2-api.chaoxing.com/v11/loginregister?code="+passwd+"&cx_xxt_passport=json&uname="+user_name+"&loginType=1&roleSelect=true"
        response = self.session.get(url, headers = self.headers)
        res_json = json.loads(response.text)
        if(res_json["status"]==True):
            print("登陆成功")
        else:
            print("登陆APP出错")
            return False
        return True

    #获取用户uid，预约需要uid
    def getUserId(self):
        """
        :return: uid or False
        """
        print("正在获取UserId")
        url = "https://sso.chaoxing.com/apis/login/userLogin4Uname.do"
        response = self.session.get(url,headers = self.headers)
        res_json = json.loads(response.text)
        # print(res_json)
        if(res_json["result"]==1):
            print("获取成功")
        else:
            print("获取UserId出错")
            return False
        print("uid:",res_json["msg"]["puid"])
        return res_json["msg"]["puid"]

    #登陆图书馆
    def loginLibrary(self,uid,dept_id = 2149):
        """
        :param uid: 前面获取到的用户uid
        :param dept_id: 不知道这个参数作何使用，实测不影响
        :return: True or False
        """
        print("正在登陆图书馆")
        url = "http://office.chaoxing.com/front/user/login/access?targetUrl=http://office.chaoxing.com/front/user/login/access?targetUrl=https%3A%2F%2Foffice.chaoxing.com%2Ffront%2Fapps%2Fseat%2Findex%3FfidEnc%3D321a0e36ee4a9fd1"
        response = self.session.get(url, headers=self.headers)
        # print(response.text)
        temp = response.text
        a = re.findall("oauth.loadInfo(.*?)done", temp)
        b = a[0]
        self.token=b[2:34]
        # print(self.token)
        url = "http://office.chaoxing.com/front/user/login/dologin?uid="+str(uid)+"&deptid="+str(dept_id)+"&token="+self.token
        response = self.session.get(url,headers = self.headers)
        res_json = json.loads(response.text)
        if(res_json["success"]==True):
            print("登陆图书馆成功")
        else:
            print("登陆图书馆出错")
            return False
        return True

    #预约座位
    def startBook(self,room_id,startTime,endTime,seat_id,day):
        """
        :param room_id: 房间编号
        :param startTime: 预约开始时间，例如13%3A30 %3A为Html中:的编码
        :param endTime: 预约结束时间，例如13%3A00
        :param seat_id: 座位号
        :param day: 日期
        :return: True or False
        """
        print("正在预约座位")
        url = "https://office.chaoxing.com/front/apps/seat/select?id="+str(room_id)+"&day="+self.day+"&backLevel=2"
        response = self.session.get(url, headers=self.headers)
        temp = response.text
        aa = re.findall("token: '(.*?)'",temp)
        bb = aa[0]
        url = "https://office.chaoxing.com/data/apps/seat/submit?roomId="+str(room_id)+"&startTime="+str(startTime)+"&endTime="+str(endTime)+"&day="+str(day)+"&seatNum="+str(seat_id)+"&token="+str(bb)
        # print(url)
        response = self.session.get(url,headers = self.headers)
        res_json = json.loads(response.text)
        if(res_json["success"]==True):
            print("预约图书馆成功")
        else:
            print("预约图书馆出错")
            return False
        return True



if __name__ == '__main__':
    schedule.every().day.at('16:59').do(job)
    while True:
        schedule.run_pending()
